package net.wangliping.android.tools;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ToolsAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	private final Context mContext;

	public ToolsAdapter(Context context) {
		mContext = context;
		mInflater = LayoutInflater.from(context);
	}

	public int getCount() {
		return ToolUtils.getActvityList().size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		
		Log.d(ToolUtils.TAG, "pos is " + position);

		ViewHolder holder;

		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.tool_grid_icon, null);

			holder = new ViewHolder();
			holder.icon = (ImageView) convertView.findViewById(R.id.icon_image);
			holder.name = (TextView) convertView.findViewById(R.id.icon_text);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		try {
			ToolUtils.ActivityInfo info = ToolUtils.getActvityList().get(position);

			Drawable d = mContext.getResources().getDrawable(info.appIcon);
			holder.icon.setBackgroundDrawable(d);
			holder.name.setText(info.appName);
			
			Log.d(ToolUtils.TAG, "NAME: " + holder.name);

		} catch (IndexOutOfBoundsException ex) {
			Log.d(ToolUtils.TAG, "Exception", ex);
		}

		return convertView;
	}

	static class ViewHolder {
		TextView name;
		ImageView icon;
	}
}
